// ==UserScript==
// @name         网课后台播放
// @namespace    http://tampermonkey.net/
// @version      2024-09-18
// @description  try to take over the world!
// @author       You
// @match        https://mooc1.chaoxing.com/mycourse/studentstudy*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=chaoxing.com
// @grant        none
// ==/UserScript==

;(async function () {
  'use strict'

  function debounce(func, wait) {
    let t
    return (...args) => {
      if (t) {
        clearTimeout(t)
      }
      t = setTimeout(func, wait, ...args)
    }
  }

  async function watchLoad(doc = document) {
    if (document.readyState === 'complete') {
      return doc
    } else {
      return new Promise((resolve) => {
        window.addEventListener('load', () => {
          resolve(doc)
        })
      })
    }
  }
  async function watchDom(q, d = document) {
    const dom = d.querySelector(q)
    if (dom) return dom
    return new Promise((resolve) => {
      requestAnimationFrame(() => {
        resolve(watchDom(q, d))
      })
    })
  }
  async function findVideo() {
    const iframe = await watchDom('iframe#iframe')
    await watchLoad(iframe.contentWindow.document)
    const videoIframe = await watchDom('iframe', iframe.contentWindow.document)
    await watchLoad(videoIframe.contentWindow.document)
    return await watchDom('video', videoIframe.contentWindow.document)
  }
  async function init() {
    await watchLoad()
    const video = await findVideo()
    console.log(video)

    video.addEventListener('play', (e) => {
      video.playbackRate = 2
    })
    video.addEventListener('pause', (e) => {
      if (video.duration - video.currentTime > 1) {
        setTimeout(() => {
          video.play()
        }, 500)
      }
    })
    video.addEventListener('ended', () => {
      console.log(video.duration, video.currentTime)
      setTimeout(() => {
        document.querySelector('#prevNextFocusNext').click()
      }, 500)
    })
    video.load()
    video.play()
    setTimeout(() => {
      video.play()
    }, 500)
  }

  await watchLoad()

  init()

  const initDebounce = debounce(init, 300)

  const observer = new MutationObserver(function (mutationsList, observer) {
    for (let mutation of mutationsList) {
      if (mutation.type === 'childList') {
        console.log('子节点被改变')
        setTimeout(() => {
          initDebounce()
        }, 300)
      }
    }
  })

  observer.observe(await watchDom('#mainid'), {
    attributes: false,
    childList: true,
    subtree: false,
  })
})()
